package com.elai.analytics.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elai.analytics.domain.ColumnHeader;
import com.elai.analytics.domain.third.CkKeepResVO;
import com.elai.common.constant.HttpStatus;
import com.elai.common.core.controller.BaseController;
import com.elai.common.core.domain.AjaxResult;
import com.elai.common.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HttpsURLConnection;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 只能推荐Controller
 *
 * @author elai
 * @date 2021-04-04
 */
@RestController
@RequestMapping("/report/keep")
public class KeepAnalyticsController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(KeepAnalyticsController.class);

    @Autowired
    private ThirdProperties thirdProperties;

    //留存分析
    private static final String KEEP_ANALYSIS ="keep/findKeep";


    @PostMapping("/keepAnalyQuery")
    public AjaxResult keepAnalyData(@RequestBody String requestJson)
    {
//        "{\"requestJson\":\"{\\\"initTypeName\\\":\\\"点击注册按钮\\\",\\\"initEventType\\\":\\\"action16\\\",\\\"initRuleTypes\\\":[],\\\"initRelationType\\\":\\\"\\\",\\\"nextTypeName\\\":\\\"点击登录按钮\\\",\\\"nextEventType\\\":\\\"\\\",\\\"nextRuleTypes\\\":[],\\\"nextRelationType\\\":\\\"\\\",\\\"userAttributes\\\":[],\\\"dynamicTags\\\":[],\\\"dateRange\\\":[\\\"2021-06-02\\\",\\\"2021-06-05\\\"],\\\"dateType\\\":\\\"day\\\",\\\"dateValue\\\":\\\"\\\",\\\"queryType\\\":\\\"leave\\\",\\\"showType\\\":\\\"1\\\",\\\"pageNum\\\":1,\\\"relationFlag\\\":false,\\\"pageSize\\\":10}\"}\n"
//        System.out.println(requestJson);
        log.info("keepAnalyQuery："+requestJson);
        JSONObject paramJson = JSONObject.parseObject(requestJson);
        JSONObject keepJson = requestJson.isEmpty()?new JSONObject(): paramJson.getJSONObject("requestJson");
        if (JSONUtil.isNull(keepJson)){
            keepJson = new JSONObject();
        }

        Map<String, Object> paramMap =new HashMap();
        int keyDay = 7;
        //{"initEvent":"MPViewScreen","followUpEvent":"MPViewScreen","startDate":"2021-05-12","endDate":"2021-05-13","keepDay":7}

        String initEvent = keepJson.getString("initEventType");
        String followUpEvent = keepJson.getString("nextEventType");
        if (StringUtils.isEmpty(initEvent)){
            initEvent = "pageview"; //Web 元素浏览
        }
        if (StringUtils.isEmpty(followUpEvent)){
            followUpEvent = "SubmitOrder"; //提交订单
        }

        String startDate = null;
        String endDate = null;
        String queryType = keepJson.getString("queryType");

        JSONArray dateArray = keepJson.getJSONArray("dateRange");
        if (JSONUtil.isNull(dateArray)){
            startDate = DateUtils.getYYYYMMDD(-6);
            endDate = DateUtils.getYYYYMMDD(-1);
        }else{
            String tempStartDate = dateArray.getString(0);
            String tempEndDate = dateArray.getString(1);
            startDate = tempStartDate.length()>10?tempStartDate.substring(0,10):tempStartDate;
            endDate = tempEndDate.length()>10?tempEndDate.substring(0,10):tempEndDate;
        }
        //概要基础指标来源
        if (startDate.equals(endDate) && keepJson.containsKey("fromQuery")){
            startDate = DateUtils.getOneDayYYYYMMDD(endDate,-6);
        }
        if (keepJson.containsKey("dateValue") && StringUtils.isNotEmpty(keepJson.getString("dateValue"))){
            keyDay = Integer.parseInt(keepJson.getString("dateValue"));
        }
        paramMap.put("initEvent",initEvent); //MPViewScreen
        paramMap.put("initEventCategory",keepJson.getString("initCategoryType")); //
        paramMap.put("followUpEvent",followUpEvent); //MPViewScreen
        paramMap.put("followUpEventCategory",keepJson.getString("nextCategoryType")); //MPViewScreen
        paramMap.put("startDate",startDate);
        paramMap.put("endDate",endDate);
        paramMap.put("keepDay",keyDay);
        paramMap.put("jsonParam",keepJson);
        if (keepJson.containsKey("applicationCode")){
            JSONArray applicationCodeList = keepJson.getJSONArray("applicationCode");
            if (applicationCodeList != null && !applicationCodeList.isEmpty()){
                paramMap.put("applicationCodeList",applicationCodeList.toJavaList(String.class));
            }
        }

        JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(),KEEP_ANALYSIS,paramMap);
        int subcode = obj.getInteger("code");
        List<CkKeepResVO> overvivwVOList=new ArrayList<>();
        if(HttpStatus.CK_SUCCESS == subcode){
            overvivwVOList = JSON.parseArray(obj.getString("data"), CkKeepResVO.class);
        }
        CkKeepResVO resVO = null;
        if (overvivwVOList != null && overvivwVOList.size() > 0){
            resVO = overvivwVOList.get(0);
        }else{
            resVO = new CkKeepResVO();
        }
        List chartTitle=new ArrayList();
        List<Integer> columnList = resVO.getDaysCount();
        for (int i=0;i<columnList.size();i++){
            if (i == 0){
                chartTitle.add("总数");
            }else{
                chartTitle.add("第"+i+"日");
            }
        }
//        if (columnList.size()>0){
//            columnList.remove(0);
//            resVO.setDaysCount(columnList);
//        }
//        List<BigDecimal> rateList = resVO.getDaysRate();
//        if (rateList.size()>0){
//            rateList.remove(0);
//            resVO.setDaysRate(rateList);
//        }



        Map<String,Object> resultMap=new HashMap();

        //列表表头
        List<ColumnHeader> tableTitle=new ArrayList<ColumnHeader>();
        tableTitle.add(new ColumnHeader("eventName","总体","",true));
        for (int i=0;i<columnList.size();i++){
            if (i == 0){
                tableTitle.add(new ColumnHeader("total","总人数","",true));
            }else{
                tableTitle.add(new ColumnHeader("firist"+(i),"第"+(i)+"日","",true));
            }
        }

        //列表数据
        List<Map<String,Object>> tableData=new ArrayList<>();

        //第一行汇总
        Map<String,Object> data1=new HashMap();
        data1.put("id","1");
        data1.put("eventName","总体");

        //明细行
        List child=new ArrayList();
        int allTotal = 0;
        int dataId = 2;
        List<Integer> rangeList = new ArrayList<>();
        List<Map<String,Object>> chartList = new ArrayList<>();

        int t=0;
        for (CkKeepResVO vo : overvivwVOList){
            List<Integer> daysCountList = vo.getDaysCount();
            int dayTotal = daysCountList.get(0);;
//            if (t > 0){
//                dayTotal = daysCountList.get(0);
//                daysCountList.remove(0);
//            }
//            int dayTotal = daysCountList.stream().reduce(Integer::sum).orElse(0);
//            t++;

            Map<String,String> data2=new HashMap();
            data2.put("id",dataId+"");
            data2.put("eventName",vo.getResDate());

//            data2.put("total",dayTotal+"");
            for (int i=0;i<daysCountList.size();i++){
                if (i == 0){
                    data2.put("total",daysCountList.get(i)+"");
                }else{
                    data2.put("firist"+(i),daysCountList.get(i)+"");
                }

            }
            child.add(data2);
            dataId++;
            allTotal = allTotal+dayTotal;
            if (rangeList.size() == 0){
                rangeList = daysCountList;
            }else{
                rangeList = ListUtil.rangeList(rangeList,daysCountList);
            }
            //chart title
//            title.add(vo.getResDate());
            //chart data
            Map<String,Object> chartMap = new HashMap<>();
            chartMap.put("name","");
            chartMap.put("type","line");
            chartMap.put("smooth",false);
            chartMap.put("data",daysCountList);
            chartList.add(chartMap);
        }
        data1.put("total",allTotal);
        for (int i=0;i<columnList.size();i++){
            if (i==0){
                data1.put("total",allTotal);
            }else{
                data1.put("firist"+(i),rangeList.get(i));
            }
        }

        data1.put("children",child);

        tableData.add(data1);

        resultMap.put("chartData",chartList);
        resultMap.put("chartTitle",chartTitle);
        resultMap.put("tableTitle",tableTitle);
        resultMap.put("tableData",tableData);
        resultMap.put("tableChildData",child);
        resultMap.put("keepInfoData",paramMap);
        return AjaxResult.success(resultMap);
    }

}
